import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/discount/discount_resp_entity.dart';
import 'package:flutter_deer/database/order_status.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/ui/cashier/cashier_page_discount.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/widgets/dialog/error_dialog.dart';
import 'package:flutter_deer/widgets/dialog/pay_success_dialog.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';
import 'package:flutter_deer/widgets/psw_input.dart';
import 'package:get/get.dart';

class DialogCardPay extends StatefulWidget {
  const DialogCardPay({
    super.key,
  });

  @override
  State<DialogCardPay> createState() => _DialogCardPayState();
}

class _DialogCardPayState extends State<DialogCardPay> {
  late Color text999;
  final mProvider = Get.find<CashierPageProvider>();
  RxString password = ''.obs;

  @override
  void initState() {
    super.initState();
    // 初始化颜色
    text999 = const Color(0xFF999999);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colours.white,
        borderRadius: BorderRadius.circular(4),
      ),
      padding: const EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 卡列表
          const Expanded(
            child: _CardConsumeList(),
          ),

          const SizedBox(width: 10),

          Column(
            children: [
              Container(
                width: 250,
                // alignment: CenterRight(),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(4.0),
                ),
                child: const CashierPageDiscount(
                  key: Key('dialog_card_pay'),
                ),
                // child: CashierPageDiscount(),
              ),

              const Spacer(),

              // 支付密码输入框
              TextInputWidget(onSubmitted: (value) {
                _confirmPay();
              }, onChanged: (value) {
                print('print--->$value');
                password.value = value;
              }),

              const SizedBox(height: 10),

              // 确认按钮
              Row(
                children: [
                  PressBlueButton(
                    width: 60,
                    height: 40,
                    fontSize: 16,
                    hoverColor: Colours.blue4B7EFE.withOpacity(0.5),
                    defaultColor: Colours.blue4B7EFE,
                    text: '取 消',
                    onPressed: () {
                      mProvider.clearDiscount();
                      Navigator.of(context).pop();
                    },
                  ),

                  const SizedBox(width: 5),

                  Obx(() => PressBlueButton(
                        width: 180,
                        height: 40,
                        fontSize: 16,
                        isEnabled: mProvider.mLiveDataDiscount.value?.available == true && password.value.length == 6,
                        hoverColor: Colors.redAccent.withOpacity(0.5),
                        defaultColor: Colors.redAccent,
                        text: '确认支付',
                        onPressed: () {
                          _confirmPay();
                        },
                      )),
                ],
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 确认支付
  void _confirmPay() {
    mProvider.orderPay(
      psw: password.value,
      onSuccess: (data, orderDes) {
        // 判断支付结果 是否需要轮询
        switch (data?.payResult?.payStatus) {
          case OrderPayStatus.SUCCESS_PAY:
            _showPaySuccessDialog(context, successInfo: orderDes);
            break;
          default:
            showDialog<void>(context: context, builder: (context) => ErrorDialog(errorMessage: orderDes));
        }
      },
      onError: (msg) {
        showDialog<void>(context: context, builder: (context) => ErrorDialog(errorMessage: msg));
      },
    );
  }

  void _showPaySuccessDialog(BuildContext context, {String successInfo = '支付成功'}) {
    showDialog<void>(
      context: context,
      builder: (context) {
        return PaySuccessDialog(
          successInfo: successInfo,
          onConfirm: () {
            mProvider.reset();
            Navigator.of(context).pop();
          },
        );
      },
    );
  }
}

// 卡列表组件
class _CardConsumeList extends StatefulWidget {
  const _CardConsumeList();

  @override
  State<_CardConsumeList> createState() => _CardConsumeListState();
}

// ... existing code ...
class _CardConsumeListState extends State<_CardConsumeList> {
  late Color text999;
  final mProvider = Get.find<CashierPageProvider>();
  int selectedIndex = -1; // 添加选中索引变量

  @override
  void initState() {
    super.initState();
    // 初始化颜色
    text999 = const Color(0xFF999999);
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() => GridView.builder(
          gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
            maxCrossAxisExtent: 340, // 每个item最大宽度100
            mainAxisSpacing: 10, // 垂直间距
            crossAxisSpacing: 10, // 水平间距
            childAspectRatio: 2.0, // 宽高比 = width/height = 100/40 = 2.5
          ),
          itemCount: mProvider.mCardList.length,
          itemBuilder: (context, index) {
            return _buildCardItem(mProvider.mCardList[index], index);
          },
        ));
  }

  // 构建列表项
  Widget _buildCardItem(DiscountItem item, int index) {
    // 计算是否可用的原因文本
    String rechargeText = _getRechargeText(item);

    // 判断卡片是否可用
    bool isAvailable = item.available == true;

    // 根据是否可用设置颜色
    Color textColor = isAvailable ? Colors.white : text999;

    // 判断是否选中
    final bool isSelected = mProvider.getCurrentDiscount?.showCardNo == item.showCardNo && item.showCardNo.isNotEmpty;

    return GestureDetector(
      onTap: () {
        // if (isAvailable) {
        setState(() {
          mProvider.selectCard(item);
        });
        // }
      },
      child: Container(
        decoration: BoxDecoration(
          color: isAvailable ? Colors.blueAccent : const Color(0xFFD4D4D4),
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.1),
              blurRadius: 4,
              offset: const Offset(0, 2),
            ),
          ],
          // 添加选中边框效果
          border: isSelected
              ? Border.all(
                  color: Colors.purple,
                  width: 2.0,
                )
              : null,
        ),
        child: Padding(
          padding: const EdgeInsets.all(15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 第一行：卡类型名称和余额
              Row(
                children: [
                  // 卡名称首字母
                  Container(
                    width: 22,
                    height: 22,
                    decoration: const BoxDecoration(
                      color: Colors.white,
                      shape: BoxShape.circle,
                    ),
                    child: Center(
                      child: Text(
                        item.getCardNameOne(),
                        style: TextStyle(
                          color: isAvailable ? const Color(0xFF13345F) : text999,
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),

                  const SizedBox(width: 8),

                  // 卡类型名称
                  Expanded(
                    child: Text(
                      item.payTypeName ?? '',
                      style: TextStyle(
                        color: textColor,
                        fontSize: 19,
                        fontWeight: FontWeight.bold,
                        overflow: TextOverflow.ellipsis,
                      ),
                      maxLines: 1,
                    ),
                  ),

                  // 余额
                  Row(
                    children: [
                      Text(
                        '¥',
                        style: TextStyle(
                          color: textColor,
                          fontSize: 12,
                        ),
                      ),
                      const SizedBox(width: 2),
                      Text(
                        item.memberAccountAmount ?? '',
                        style: TextStyle(
                          color: textColor,
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ],
              ),

              const SizedBox(height: 15),

              // 第二行：卡号和操作按钮
              Text(
                item.showCardNo ?? '',
                style: TextStyle(
                  color: textColor,
                  fontSize: 14,
                  overflow: TextOverflow.ellipsis,
                ),
                maxLines: 1,
              ),

              const SizedBox(height: 15),

              // 第三行：不可用原因 - 限制高度避免溢出
              Row(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                Text(
                  '',
                  style: TextStyle(
                    color: textColor,
                    fontSize: 12,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                if (item.unavailableMsg.isNotEmpty)
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 3),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(10),
                    ),
                    child: Text(
                      '${item.unavailableMsg}',
                      style: TextStyle(
                        color: text999,
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
              ]),
            ],
          ),
        ),
      ),
    );
  }

// ... existing code ...

  String _getRechargeText(DiscountItem item) {
    final bool enterpriseCard = item.isEnterpriseCard();

    if (enterpriseCard) {
      return '企业卡不可混合支付';
    } else {
      return '企业卡不可混合支付';
    }
  }

  // 辅助方法：判断字符串是否表示大于0的数字
  bool _isMoreThanZero(String value) {
    try {
      return double.parse(value) > 0;
    } catch (e) {
      return false;
    }
  }
}
